#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
报表生成系统 - 生成作业报告
"""
from datetime import datetime
import json
import os

class ReportGenerator:
    """报表生成器"""
    
    @staticmethod
    def generate_work_session_report(session_data, gps_track=None, output_format='html'):
        """
        生成作业会话报告
        session_data: 作业会话数据
        gps_track: GPS轨迹数据
        output_format: 输出格式 ('html', 'json')
        """
        if output_format == 'html':
            return ReportGenerator._generate_html_report(session_data, gps_track)
        elif output_format == 'json':
            return ReportGenerator._generate_json_report(session_data, gps_track)
        else:
            raise ValueError(f"不支持的格式: {output_format}")
    
    @staticmethod
    def _generate_html_report(session_data, gps_track):
        """生成HTML格式报告"""
        
        html_template = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>作业报告 - {session_id}</title>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{ font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }}
        .report-container {{ max-width: 900px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
        .header {{ text-align: center; border-bottom: 3px solid #2196F3; padding-bottom: 20px; margin-bottom: 30px; }}
        .header h1 {{ color: #2196F3; font-size: 28px; margin-bottom: 10px; }}
        .header .meta {{ color: #666; font-size: 14px; }}
        .section {{ margin-bottom: 30px; }}
        .section h2 {{ color: #333; font-size: 20px; border-left: 4px solid #2196F3; padding-left: 10px; margin-bottom: 15px; }}
        .info-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }}
        .info-item {{ background: #f9f9f9; padding: 15px; border-radius: 5px; }}
        .info-label {{ color: #666; font-size: 12px; margin-bottom: 5px; }}
        .info-value {{ color: #333; font-size: 18px; font-weight: bold; }}
        .stats-table {{ width: 100%; border-collapse: collapse; }}
        .stats-table th, .stats-table td {{ padding: 12px; text-align: left; border-bottom: 1px solid #e0e0e0; }}
        .stats-table th {{ background: #f5f5f5; color: #333; font-weight: bold; }}
        .footer {{ text-align: center; color: #999; font-size: 12px; margin-top: 40px; padding-top: 20px; border-top: 1px solid #e0e0e0; }}
        @media print {{ body {{ background: white; }} .report-container {{ box-shadow: none; }} }}
    </style>
</head>
<body>
    <div class="report-container">
        <div class="header">
            <h1>甘蔗农机作业报告</h1>
            <div class="meta">会话ID: {session_id} | 生成时间: {report_time}</div>
        </div>
        
        <div class="section">
            <h2>基本信息</h2>
            <div class="info-grid">
                <div class="info-item">
                    <div class="info-label">机器人编号</div>
                    <div class="info-value">{robot_id}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">地块编号</div>
                    <div class="info-value">{field_id}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">路径编号</div>
                    <div class="info-value">{path_id}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">作业状态</div>
                    <div class="info-value">{status}</div>
                </div>
            </div>
        </div>
        
        <div class="section">
            <h2>时间信息</h2>
            <table class="stats-table">
                <tr>
                    <th>开始时间</th>
                    <td>{start_time}</td>
                </tr>
                <tr>
                    <th>结束时间</th>
                    <td>{end_time}</td>
                </tr>
                <tr>
                    <th>作业时长</th>
                    <td>{duration}</td>
                </tr>
            </table>
        </div>
        
        <div class="section">
            <h2>作业统计</h2>
            <table class="stats-table">
                <tr>
                    <th>作业面积</th>
                    <td>{area_covered} 亩 ({area_covered_m2} 平方米)</td>
                </tr>
                <tr>
                    <th>行驶距离</th>
                    <td>{distance_traveled} 米</td>
                </tr>
                <tr>
                    <th>燃油消耗</th>
                    <td>{fuel_consumed} 升</td>
                </tr>
                <tr>
                    <th>作业效率</th>
                    <td>{efficiency} 亩/小时</td>
                </tr>
            </table>
        </div>
        
        <div class="section">
            <h2>GPS信息</h2>
            <table class="stats-table">
                <tr>
                    <th>起始位置</th>
                    <td>纬度: {start_lat}, 经度: {start_lon}</td>
                </tr>
                <tr>
                    <th>结束位置</th>
                    <td>纬度: {end_lat}, 经度: {end_lon}</td>
                </tr>
                <tr>
                    <th>轨迹点数</th>
                    <td>{track_points} 个</td>
                </tr>
            </table>
        </div>
        
        <div class="section">
            <h2>备注</h2>
            <div style="background: #f9f9f9; padding: 15px; border-radius: 5px;">
                {notes}
            </div>
        </div>
        
        <div class="footer">
            <p>甘蔗农机智能管控平台 | 自动生成报告</p>
            <p>© 2024 版权所有</p>
        </div>
    </div>
</body>
</html>
        """
        
        # 格式化数据
        start_time = session_data.get('start_time', '')
        end_time = session_data.get('end_time', '')
        duration_seconds = session_data.get('duration_seconds', 0)
        
        # 计算时长
        hours = duration_seconds // 3600
        minutes = (duration_seconds % 3600) // 60
        seconds = duration_seconds % 60
        duration_str = f"{hours}小时{minutes}分钟{seconds}秒"
        
        # 计算作业效率
        area_covered = session_data.get('area_covered', 0)
        efficiency = (area_covered / (duration_seconds / 3600)) if duration_seconds > 0 else 0
        
        # 计算平方米
        area_covered_m2 = area_covered * 666.67
        
        # 填充模板
        html = html_template.format(
            session_id=session_data.get('id', 'N/A'),
            report_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            robot_id=session_data.get('robot_id', 'N/A'),
            field_id=session_data.get('field_id', 'N/A') or '未指定',
            path_id=session_data.get('path_id', 'N/A') or '未指定',
            status=session_data.get('status', 'N/A'),
            start_time=start_time,
            end_time=end_time or '进行中',
            duration=duration_str,
            area_covered=f"{area_covered:.2f}",
            area_covered_m2=f"{area_covered_m2:.2f}",
            distance_traveled=f"{session_data.get('distance_traveled', 0):.2f}",
            fuel_consumed=f"{session_data.get('fuel_consumed', 0):.2f}",
            efficiency=f"{efficiency:.2f}",
            start_lat=f"{session_data.get('start_lat', 0):.6f}",
            start_lon=f"{session_data.get('start_lon', 0):.6f}",
            end_lat=f"{session_data.get('end_lat', 0):.6f}" if session_data.get('end_lat') else 'N/A',
            end_lon=f"{session_data.get('end_lon', 0):.6f}" if session_data.get('end_lon') else 'N/A',
            track_points=len(gps_track) if gps_track else 0,
            notes=session_data.get('notes', '无') or '无'
        )
        
        return html
    
    @staticmethod
    def _generate_json_report(session_data, gps_track):
        """生成JSON格式报告"""
        report = {
            'report_type': 'work_session',
            'generated_at': datetime.now().isoformat(),
            'session': session_data,
            'gps_track_points': len(gps_track) if gps_track else 0,
            'gps_track': gps_track if gps_track else []
        }
        return json.dumps(report, ensure_ascii=False, indent=2)
    
    @staticmethod
    def save_report(content, filename, output_dir='reports'):
        """保存报告到文件"""
        os.makedirs(output_dir, exist_ok=True)
        filepath = os.path.join(output_dir, filename)
        
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(content)
        
        return filepath

# 创建全局实例
report_gen = ReportGenerator()

